package servlet.user;

import service.UserService;
import service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 作者：杨晋
 */
@WebServlet("/user/removeById")
public class RemoveById {
    UserService userService = new UserServiceImpl();

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取要删除的用户ID
        String userIdStr = req.getParameter("user_id");

        if (userIdStr == null || userIdStr.isEmpty()) {
            resp.setContentType("text/html;charset=UTF-8");
            resp.getWriter().write("<script>alert('用户ID不能为空');</script>");
            return;
        }

        try {
            int userId = Integer.parseInt(userIdStr);

            // 调用Service层删除用户
            boolean flag = userService.removeById((int) userId);

            if (flag) {
                // 删除成功，重定向到用户列表页面或其他页面
                resp.sendRedirect("/user/list.jsp");
            } else {
                // 删除失败，输出错误提示
                resp.setContentType("text/html;charset=UTF-8");
                resp.getWriter().write("<script>alert('删除失败');</script>");
            }
        } catch (NumberFormatException e) {
            // 捕获用户ID解析错误
            resp.setContentType("text/html;charset=UTF-8");
            resp.getWriter().write("<script>alert('无效的用户ID');</script>");
        }
    }
}
